/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Used modules */
const {
	PREF_NAME_POLICY_CLOSE_FINISHED
	,PREF_NAME_POLICY_DOWNLOADS
	,PREF_NAME_POLICY_SCREENSHOTS
	,PREF_NAME_POLICY_NO_PRIV_URI
	,PREF_NAME_POLICY_NO_PRIV_SCRIPTING
	,PREF_NAME_POLICY_PB_CONTEXT
	,PREF_NAME_POLICY_SCRIPT_TIMEOUT
} = require('../pref-names.json');

const _prefs = require('./preferences').openPreferences([
	PREF_NAME_POLICY_CLOSE_FINISHED
	,PREF_NAME_POLICY_DOWNLOADS
	,PREF_NAME_POLICY_SCREENSHOTS
	,PREF_NAME_POLICY_NO_PRIV_URI
	,PREF_NAME_POLICY_NO_PRIV_SCRIPTING
	,PREF_NAME_POLICY_PB_CONTEXT
	,PREF_NAME_POLICY_SCRIPT_TIMEOUT
]);

const PB_CONTEXT_BOTH = 0, PB_CONTEXT_NORMAL = 1, PB_CONTEXT_PRIVATE = 2;


/* Internal APIs */

// policy manager
const createManager = scriptURI => {
	const prefs = _prefs;
	
	let openNormalWindow = true, openPrivateWindow = true;
	let downloads = false, screenshots = false;
	let privOpen = false, privScripts = false;
	let invisiblePages = false; // unimplemented
	
	let sessionTimeout = 0 | prefs[PREF_NAME_POLICY_SCRIPT_TIMEOUT];
	let autoClose = !!prefs[PREF_NAME_POLICY_CLOSE_FINISHED];
	
	// Private browsing
	switch (prefs[PREF_NAME_POLICY_PB_CONTEXT]) {
		case PB_CONTEXT_NORMAL: openPrivateWindow = false; break;
		case PB_CONTEXT_PRIVATE: openNormalWindow = false; break;
	}
	
	// Browser interfaces
	if (!prefs[PREF_NAME_POLICY_NO_PRIV_URI]) privOpen = true;
	if (!prefs[PREF_NAME_POLICY_NO_PRIV_SCRIPTING]) privScripts = privOpen && true;
	
	// Permissions
	if (prefs[PREF_NAME_POLICY_DOWNLOADS]) downloads = true;
	if (prefs[PREF_NAME_POLICY_SCREENSHOTS]) screenshots = true;
	
	return Object.freeze({
		__proto__: null
		,disallowDownloads () {
			downloads = false;
		}
		,disallowScreenshots () {
			screenshots = false;
		}
		,disallowOpenNonPrivate () {
			openNormalWindow = false;
		}
		,disallowOpenPrivate () {
			openPrivateWindow = false;
		}
		,disallowBrowserPages () {
			privOpen = privScripts = false;
		}
		,disallowBrowserScripting () {
			privScripts = false;
		}
		,disallowInvisiblePages () {
			invisiblePages = false;
		}
		,set autoClose (value) {
			autoClose = !!value;
		}
		,get autoClose () {return !!autoClose}
		,get downloads () {return !!downloads}
		,get screenshots () {return !!screenshots}
		,get openPrivate () {return !!openPrivateWindow}
		,get openNonPrivate () {return !!openNormalWindow}
		,get browserPages () {return !!privOpen}
		,get browserScripting () {return !!privScripts}
		,get invisiblePages () {return !!invisiblePages}
		,get sessionTimeout () {return 0|sessionTimeout}
		,set sessionTimeout (t) {
			sessionTimeout = 0|t;
		}
	});
};

/* Exports */
exports.createManager = createManager;

// vim: ts=4 noet ai

